import { Injectable, Injector, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {
  MenuService,
  SettingsService,
  TitleService,
  ALAIN_I18N_TOKEN,
} from '@delon/theme';
import { ACLService } from '@delon/acl';
import { TranslateService } from '@ngx-translate/core';
import { I18NService } from '@core/i18n/i18n.service';
import { LoginService } from '../../service/login.service';
import { Constant } from '@core/constant';
import { UserService } from '../../service/user/user.service';

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
  constructor(

    private menuService: MenuService,
    private translate: TranslateService,
    @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
    private settingService: SettingsService,
    private aclService: ACLService,
    private titleService: TitleService,
    private httpClient: HttpClient,
    private injector: Injector,
    // private router: Router,
    private cnt: Constant
  ) {}

  load(): Promise<any> {
    // only works with promises
    // https://github.com/angular/angular/issues/15088
    return new Promise((resolve, reject) => {
      zip(
        this.httpClient.get(`assets/tmp/i18n/${this.i18n.defaultLang}.json`),
        this.httpClient.get('assets/tmp/app-data.json'),
        this.injector.get(LoginService).info(""),
        this.injector.get(LoginService).menu(""),
      )
        .pipe(
          // 接收其他拦截器后产生的异常消息
          catchError((err) => {
              resolve(null);
              return [];
          })
        )
        .subscribe(
          ([langData, appData, info, menu]) => {
            // setting language data
            this.translate.setTranslation(this.i18n.defaultLang, langData);
            this.translate.setDefaultLang(this.i18n.defaultLang);

            // application data
            const res: any = appData;
            // 应用信息：包括站点名、描述、年份
            this.settingService.setApp(res.app);
            console.log("info111111"+JSON.stringify(info));
            console.log(info)
            if(info.data===null||info.data===""){
              // this.router.navigate(['/passport/login']);
              return false;
            }{
              // 用户信息：包括姓名、头像、邮箱地址
              console.log("info.data.username"+JSON.stringify(info.data.userName));
              this.settingService.setUser({

                  name: info.data.realName,
                  username: info.data.userName,
                  id: info.data.id,
                  email: '',
                  sysorgCode:info.data.currentDepart.orgCode,

                avatar: `${info.image ? `${this.cnt.baseUrl}/api/file/avatar/` + info.image : "./assets/tmp/img/avatar.jpg"}`,
                  elements: info.elements
              });
            }
            // SMS用户信息
            // 获取sms用户信息
            // this.injector.get(UserService).info3(info.id).subscribe(data => {
            //   if (data['status'] === 200) {
            //       let user = this.settingService.user;
            //       if (data['data']) {
            //           user.brand = data['data'].brand;
            //           user.currency = data['data'].currency;
            //           user.siteCode = data['data'].siteCode;
            //           user.userinfoId = data['data'].id;
            //           user.alias = data['data'].name;
            //           user.level = data['data'].userLevel;
            //           user.isManager = false;
            //           user.bodyId = data['data'].bodyId;
            //           user.bodyUsername = data['data'].bodyUsername;
            //       } else {
            //           // 管理账号
            //           user.isManager = true;
            //       }
            //       this.settingService.setUser(user);
            //   }
            // })
            // ACL：设置权限为全量
            this.aclService.setFull(true);
            // 初始化菜单
            if(menu.data===null||menu.data===""){
              // this.router.navigate(['/passport/login']);
              return false;
            }else{
              console.log("**************menu"+JSON.stringify(menu));
              this.menuService.add(menu.data as any);
              // 设置页面标题的后缀
              this.titleService.suffix = res.app.name;
            }

          },
          () => {},
          () => {
            resolve(null);
          },
        );
    });
  }
}
